package cn.chinaflame.pagodas.service;

import java.sql.SQLException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;

import cn.chinaflame.pagodas.entity.PaLightsLog;
import cn.chinaflame.pagodas.enums.CodeEnum;
import cn.chinaflame.pagodas.repository.PaLightsLogRepository;
import cn.chinaflame.pagodas.utils.ParamPreconditions;
import cn.chinaflame.pagodas.utils.stl.DateUtils;

 /**
  * 寻灯，安灯，清灯，检查灯位日志记录Service
  * @author pengcheng.zhao
  *
  */
@Service
public class PaLightsLogService{
	
	    private static final Logger log = LoggerFactory.getLogger(PaLightsLogService.class);

	    @Autowired
	    private JdbcTemplate jdbcTemplate;
	    
	/**
	 * 通过日期查询
	 * @param date
	 * @return
	 */
    public List<PaLightsLog> findByCreatetime(String date) {
    	log.info("PaLightsLogService:findByCreatetime:date:{}",date);
    	ParamPreconditions.checkDateByFmt(date, DateUtils.DATE_DEFAULT_PATTERN);
    	String sql = "select * from pa_lights_log where date_format(createtime,'%Y-%m-%d')= date_format(?,'%Y-%m-%d')";
    	List<PaLightsLog> list = jdbcTemplate.query(sql, new Object[] {date}, (RowMapper<PaLightsLog>) (rs, rowNum) -> {
    		PaLightsLog result = new PaLightsLog();
    		result.setId(rs.getLong("id"));
    		result.setParams(rs.getString("params"));
			result.setCreatetime(rs.getString("createtime"));
			result.setLightno(rs.getString("lightno"));
			result.setMessage(rs.getString("message"));
			result.setResult(rs.getInt("result"	));
			result.setMethod(rs.getString("method"));
			result.setIp(rs.getString("ip"));
			result.setState(rs.getInt("state"));
			result.setOpsort(rs.getString("opsort"));
			return result;
		});
    	log.info("PaLightsLogService:findByCreatetime:list.size()={}",list.size());
		return list;
	}
    
    /**
     * 通过灯号查询
     * @param lightno
     * @return
     */
    public List<PaLightsLog> findByLightno(String lightno) {
    	log.info("PaLightsLogService:findByLightno:lightno:{}",lightno);
    	ParamPreconditions.checkNotEmpty(lightno, CodeEnum.FAIL.getCode(), "灯号不能为空！");
    	ParamPreconditions.checkArgument(lightno.length() == 10, CodeEnum.FAIL.getCode(), "灯号必须为10位！");
    	String sql = "select * from pa_lights_log where lightno = ?";
    	List<PaLightsLog> list = jdbcTemplate.query(sql, new Object[] {lightno}, (RowMapper<PaLightsLog>) (rs, rowNum) -> {
    		PaLightsLog result = new PaLightsLog();
    		result.setId(rs.getLong("id"));
    		result.setParams(rs.getString("params"));
			result.setCreatetime(rs.getString("createtime"));
			result.setLightno(rs.getString("lightno"));
			result.setMessage(rs.getString("message"));
			result.setResult(rs.getInt("result"	));
			result.setMethod(rs.getString("method"));
			result.setIp(rs.getString("ip"));
			result.setState(rs.getInt("state"));
			result.setOpsort(rs.getString("opsort"));
			return result;
		});
    	log.info("PaLightsLogService:findByLightno:list.size()={}",list.size());
		return list;
	}
    
    /**
     * 通过消息查询
     * @param msg
     * @return
     */
    public List<PaLightsLog> findByMessage(String msg) {
    	log.info("PaLightsLogService:findByMessage:msg:{}",msg);
    	ParamPreconditions.checkNotEmpty(msg, CodeEnum.FAIL.getCode(), "坏灯信息不能为空！");
    	String sql = "select * from pa_lights_log where message = ?";
    	List<PaLightsLog> list = jdbcTemplate.query(sql, new Object[] {msg}, (RowMapper<PaLightsLog>) (rs, rowNum) -> {
    		PaLightsLog result = new PaLightsLog();
    		result.setId(rs.getLong("id"));
    		result.setParams(rs.getString("params"));
			result.setCreatetime(rs.getString("createtime"));
			result.setLightno(rs.getString("lightno"));
			result.setMessage(rs.getString("message"));
			result.setResult(rs.getInt("result"	));
			result.setMethod(rs.getString("method"));
			result.setIp(rs.getString("ip"));
			result.setState(rs.getInt("state"));
			result.setOpsort(rs.getString("opsort"));
			return result;
		});
    	log.info("PaLightsLogService:findByMessage:list.size()={}",list.size());
		return list;
	
	}
    /**
     * 
     * @param light
     * @return
     */
    public int addLightLog(PaLightsLog light){
    	log.info("PaLightsLogService:addLightLog:light:{}",light.toString());
    	String sql = "insert into pa_lights_log(method,params,createtime,lightno,result,ip,state,opsort,message)values(?,?,now(),?,?,?,0,?,?) ";
    	int result = jdbcTemplate.update(sql,new Object[] {light.getMethod(),light.getParams(),light.getLightno(),light.getResult(),light.getIp(),light.getOpsort(),light.getMessage()});
    	log.info("PaLightsLogService:addLightLog:result:{}",result);
    	return result;
	}
    
   /**
    * 批量插入接口
    * @param lights
    * @return
    */
    public int[] batchAddLight(List<PaLightsLog> lights){
    	log.info("PaLightsLogService:batchAddLight:lights:{}",JSONArray.toJSONString(lights));
    	String sql = "insert into pa_lights_log(method,params,createtime,lightno,result,state,opsort,message)values(?,?,now(),?,?,0,?,?) ";
    	int[] result = null;
		 try {
				result = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
					@Override
					public int getBatchSize() {
						return lights.size();
					}
					@Override
					public void setValues(java.sql.PreparedStatement ps, int i) throws SQLException {
						PaLightsLog log = lights.get(i);
						ps.setString(1, log.getMethod());
						ps.setString(2,log.getParams());
						ps.setString(3, log.getLightno());
						ps.setInt(4, log.getResult());
						ps.setString(5, log.getOpsort());
						ps.setString(6, log.getMessage());
					}
				});
		 } catch (Exception e) {
				log.error(e.getMessage());
		 }
		 log.info("PaLightsLogService:batchAddLight:result:{}",result);
			return result;
	}
}
